﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Umbraco.Core.Models;
using Umbraco.Web.WebApi;
using MarkdownSharp;

namespace Com.UmbracoChina.Controllers
{
    /// <summary>
    /// 搜索接口控制器
    /// </summary>
    public class DocumentationController: UmbracoApiController
    {
        public IEnumerable<Document> Search()
        {
            List<Document> result = new List<Document>();

            string keyword = string.Empty;
            if (HttpContext.Current.Request.Form["keyword"] != null)
            {
                keyword = HttpContext.Current.Request.Form["keyword"].ToString();
                if (!string.IsNullOrEmpty(keyword))
                {
                    keyword = HttpContext.Current.Server.UrlDecode(keyword);
                }
            }
            

            if (!string.IsNullOrEmpty(keyword))
            {
                var maybe = Umbraco.TypedSearch(keyword, false, "ExternalDocumentSearcher");
                if (maybe.Any(x => x.DocumentTypeAlias == "documentationDetail"))
                {
                    IEnumerable<IPublishedContent> searchs = maybe.Where(x => x.DocumentTypeAlias == "documentationDetail");
                    Markdown md = new Markdown();
                    foreach (IPublishedContent item in searchs)
                    {
                        result.Add(new Document()
                        {
                            title = item.Name
                            ,
                            url = item.Url
                            ,
                            content = Umbraco.Truncate(Umbraco.StripHtml(md.Transform(item.GetProperty("documentContent").Value.ToString())), 60).ToString()
                        });
                    }
                }
            }

            
            return result;
        }
    }


    public class Document
    {   
        public string title { get; set; }
        public string url { get; set; }
        public string content { get; set; }
    }
}